package com.credithc.signature.manager.controller;

import com.alibaba.fastjson.JSONArray;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.signature.common.constant.SealConstant;
import com.credithc.signature.common.po.FddSealInfo;
import com.credithc.signature.common.po.SealInfo;
import com.credithc.signature.common.ro.SealInfoReplenishRo;
import com.credithc.signature.common.ro.manager.SealInfoRo;
import com.credithc.signature.common.service.SealInfoService;
import com.credithc.signature.common.service.lanmao.LanmaoRegisterService;
import com.credithc.signature.common.utils.UUIDUtil;
import com.credithc.signature.common.vo.manager.DictionaryVo;
import com.credithc.signature.common.vo.manager.SealInfoVo;
import com.credithc.signature.manager.client.AuthClient;
import com.credithc.signature.manager.service.AuthorizationService;
import com.credithc.signature.manager.service.CfcaSealService;
import com.credithc.signature.manager.utils.FileUploadUtil;
import com.credithc.signature.manager.utils.ManagerFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描 述: 手动制章Controller<br/>
 * 作 者: JingBo Hu<br/>
 * 创 建：2019/5/24 16:55<br/>
 * 版 本：v1.0.0<br>
 */
@RestController
@RequestMapping("/manager/scs/v2")
@Slf4j
public class SealController {

    private static final String SUCCESS = "SUCCESS";

    @Autowired
    MessageFactory messageFactory;

    @Autowired
    SealInfoService sealInfoService;

    @Autowired
    CfcaSealService cfcaSealService;

    @Autowired
    AuthClient authClient;

    @Autowired
    AuthorizationService authorizationService;

    @Autowired
    LanmaoRegisterService lanmaoRegisterService;


    /**
     * 查询所有
     *
     * @param sealInfoRo
     * @return
     */
    @PostMapping("/sealInfo/list")
    public Message queryAll(@RequestHeader("token") String token, @RequestBody SealInfoRo sealInfoRo, HttpServletRequest request) {
        try {
            SealInfoRo newSealInfoRo = null;
            try {
                newSealInfoRo = authorizationService.authSealInfoRo(sealInfoRo, token, request);
            } catch (Exception e) {
                return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, e.getMessage());
            }
            PageInfo<SealInfoVo> pageInfo = sealInfoService.queryAll(newSealInfoRo);
            Map<String, Object> map = new HashMap<>(16);
            map.put("pageInfo", pageInfo);
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
        } catch (Exception e) {
            log.error("获取授权时发生异常", e);
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, "获取授权时发生异常");
        }
    }

    /**
     * 查询证书类型
     *
     * @param
     * @return
     */
    @PostMapping("/sealInfo/certType/list")
    public Message queryCertType() {
        List<DictionaryVo> vos = sealInfoService.queryCertType();
        Map map = new HashMap<>(16);
        map.put("list", vos);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }


    /**
     * 查询证书类型
     *
     * @param
     * @return
     */
    @PostMapping("/sealInfo/certType/list/p")
    public Message queryCertTypeP() {
        List<DictionaryVo> vos = sealInfoService.queryCertTypeP();
        Map map = new HashMap<>(16);
        map.put("list", vos);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }


    /**
     * 查询单条--中金
     *
     * @param id
     * @return
     */
    @GetMapping("/sealInfo/one/{id}")
    public Message queryOne(@PathVariable Long id) {
        SealInfoVo sealInfoVo = sealInfoService.queryOne(id);
        Map map = new HashMap<>(16);
        map.put("vo", sealInfoVo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    /**
     * 查询单条--法大大
     *
     * @param id
     * @return
     */
    @GetMapping("/sealInfo/fdd/one/{id}")
    public Message queryFddOne(@PathVariable Long id, @RequestParam("appId") String appId) {
        SealInfoVo sealInfoVo = sealInfoService.queryOne2(id, appId);
        Map map = new HashMap<>(16);
        map.put("vo", sealInfoVo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    /**
     * 新增--中金
     *
     * @param sealInfoRo
     * @return
     */
    @PostMapping("/sealInfo/saveZj")
    public Message saveZj(@RequestBody SealInfoRo sealInfoRo, HttpServletRequest request) throws Exception {
        String result = null;
        SealInfo sealInfo = cfcaSealService.queryOne(sealInfoRo);
        if (sealInfo == null) {
            //调三方制章
            result = cfcaSealService.makeSealAutomation(sealInfoRo);
        } else {
            //本地制章
            result = cfcaSealService.makeSealInLocal(sealInfoRo, request);
        }
        //返回制章结果
        if (SUCCESS.equals(result)) {
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
        } else {
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, result);
        }
    }

    /**
     * 新增--法大大
     *
     * @param sealInfoRo
     * @return
     */
    @PostMapping("/sealInfo/saveFdd")
    public Message saveFdd(@RequestBody SealInfoRo sealInfoRo, @RequestHeader("token") String token, HttpServletRequest request) throws Exception {
        // 获取channelNo
        SealInfoRo newSealInfoRo = null;
        try {
            newSealInfoRo = authorizationService.authSealInfoRo(sealInfoRo, token, request);
        } catch (Exception e) {
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, e.getMessage());
        }
        String result = null;
        FddSealInfo sealInfo = cfcaSealService.queryOne2(sealInfoRo);
        if (sealInfo == null) {
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, "公章不存在,请先完成法大大企业认证流程！");
        } else {
            //本地制章
            sealInfoRo.setChannelNo(newSealInfoRo.getChannelNo());
            result = cfcaSealService.makeSealInLocal2(sealInfoRo, request);
        }
        //返回制章结果
        if (SUCCESS.equals(result)) {
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
        } else {
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, result);
        }
    }


    /**
     * 根据证件号码和证件类型
     *
     * @param sealInfoRo
     * @return
     * @throws Exception
     */
    @PostMapping("/sealInfo/querySealInfo")
    public Message querySealInfo(@RequestBody SealInfoRo sealInfoRo) throws Exception {
        SealInfo sealInfo = cfcaSealService.queryOne(sealInfoRo);
        Map map = new HashMap<>(16);
        map.put("vo", sealInfo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    /**
     * 查询sealName
     *
     * @param sealInfoRo
     * @return
     */
    @PostMapping("/sealInfo/searchSealName")
    public Message searchSealName(@RequestBody SealInfoRo sealInfoRo) {
        JSONArray array = sealInfoService.searchSealName(sealInfoRo);
        Map map = new HashMap<>(16);
        map.put("list", array);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    /**
     * 修改状态
     *
     * @param
     * @return
     */
    @PostMapping("/sealInfo/updateSts")
    public Message updateSts(@RequestHeader("token") String token, HttpServletRequest request, @RequestBody SealInfoRo sealInfoRo) {
        List<String> channelNo = null;
        try {
            channelNo = authorizationService.authChannelNo(token, request);
        } catch (Exception e) {
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, e.getMessage());
        }
        sealInfoService.updateSts(sealInfoRo, channelNo.get(0));
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    /**
     * 上传图片
     *
     * @param
     * @return
     */
    @PostMapping("/sealInfo/upload")
    public Message upload(@RequestParam("file") MultipartFile file) throws Exception {
        File imageFile = ManagerFileUtil.multipartFileToFile(file);
        String pictureId = FileUploadUtil.upload(imageFile, SealConstant.IMG, file.getOriginalFilename(), UUIDUtil.getUUID());
        Map map = new HashMap<>(16);
        map.put("pictureId", pictureId);
        map.put("fileName", file.getOriginalFilename());
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    @GetMapping("/lanmao")
    public Message lanmaoSeal(String sealCode) {
        String s = "";
        try {
            s = lanmaoRegisterService.registerEnt(sealCode);
        } catch (Exception e) {
            e.printStackTrace();
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, e.getMessage());

        }
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, s);
    }

    @GetMapping("/replenish/list")
    public Message replenishList() {
        PageInfo<SealInfo> pageInfo = sealInfoService.selectReplenish();
        Map map = new HashMap<>(16);
        map.put("pageInfo", pageInfo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    @GetMapping("/replenish/info/{id}")
    public Message replenishInfo(@PathVariable Long id) {
        SealInfo sealInfo = sealInfoService.selectReplenishInfo(id);
        Map map = new HashMap<>(16);
        map.put("vo", sealInfo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, map);
    }

    @PostMapping("/replenish/save")
    public Message replenishSave(@RequestBody SealInfoReplenishRo sealInfo) {
        ///SealInfo sealInfo =  sealInfoService.selectReplenishInfo(id);
        if (StringUtils.isNotBlank(sealInfo.getPictureId())) {
            byte[] image = FileUploadUtil.downloadImg(sealInfo.getPictureId());
            sealInfo.setImage(image);
        }
        sealInfoService.replenishSave(sealInfo);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }


}
